// middleware/authMiddleware.js
const jwt = require('jsonwebtoken');

// const { createClient } = require('redis');

function authMiddleware(req, res, next) {
    const token = req.header('Authorization') && req.header('Authorization').replace('Bearer ', '');

    if (!token) {
        return res.status(401).json({
            code: 401,
            success: false,
            message: 'No token provided',
        });
    }

    jwt.verify(token, process.env.JWT_SECRET, async (err, decoded) => {
        if (err) {
            return res.status(401).json({
                code: 401,
                success: false,
                message: 'Unauthorized',
            });
        }
        console.log('decoded--', decoded);
        const userId = decoded.id; // 获取用户 ID
        // const client = createClient({
        //     url: 'redis://127.0.0.1:6379'
        // });

        // 连接到 Redis
        // await client.connect();
        // 获取值
        // const value = await client.get(`token:${userId}`);

        // if (err || value !== token) return res.sendStatus(403).json({
        //     code: 403,
        //     success: false,
        //     message: 'Unauthorized',
        // }); // 访问令牌不匹配
        req.user = decoded; // 将解码后的用户信息附加到请求
        next();
     
    });
}

module.exports = authMiddleware;